package com.guowen.myaccount.frag_record;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.guowen.myaccount.R;
import com.guowen.myaccount.RecordActivity;
import com.guowen.myaccount.db.AccManageBean;
import com.guowen.myaccount.db.AccountBean;
import com.guowen.myaccount.db.DBManager;
import com.guowen.myaccount.db.TypeBean;
import com.guowen.myaccount.utils.BeiZhuDialog;
import com.guowen.myaccount.utils.ChoiceDialog;
import com.guowen.myaccount.utils.KeyBoardUtils;
import com.guowen.myaccount.utils.SelectTimeDialog;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 记录页面当中的支出模块
 */
public abstract class BaseRecordFragment extends Fragment implements View.OnClickListener, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{

    private KeyboardView keyboardView;
    EditText moneyEdit;
    ImageView typeImage;
    TextView typeText;
    private TextView beizhuText;
    private TextView timeText;
    private TextView accountText;

    int selectAccPos = 0;

    private GridView typeGrid;

    List<TypeBean> typeList;
    TypeBaseAdapter adapter;
    AccountBean accountBean; //将需要插入到记账本当中的数据保存成对象的形式
    List<AccManageBean> accManageBeans;
    AccManageBean accManageBean;
    int type; //表示是修改1还是添加0
    int id;
    int[] menuId;
    float old_money;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getActivity().getIntent();
        this.type = intent.getIntExtra("type",0);
        this.id = intent.getIntExtra("id",0);
        this.old_money = intent.getFloatExtra("money",0);

        accountBean = new AccountBean(); // 创建对象
        accountBean.setTypename("其他");
        accountBean.setsImageId(R.mipmap.ic_qita_fs);

        if (type == 1){
            accountBean = (AccountBean) intent.getSerializableExtra("click_bean");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_outcome, container, false);

        initView(view);
        setAccountData();
        setInitTime();
        // 给GridView填充数据的方法
        loadDataGrid();
        // 设置GridView每一项的点击事件
        setGVListener();

        if (type == 1)
            setOldAccountData();

        return view;
    }

    private void setOldAccountData(){
        moneyEdit.setText(accountBean.getMoney()+"");
        typeImage.setImageResource(accountBean.getsImageId());
        typeText.setText(accountBean.getTypename());
        beizhuText.setText(accountBean.getBeizhu());


    }



    // 初始化账户栏内容
    @SuppressLint("LongLogTag")
    private void setAccountData() {
        accManageBeans = DBManager.getAccManList();
        if (type == 1){
            String name1 = accountBean.getAccount();
            for (int i = 0; i < accManageBeans.size(); i++) {
                String name2 = accManageBeans.get(i).getTypename();
                if (name1.equals(name2)) {
                    selectAccPos = i;
                    accManageBean = accManageBeans.get(selectAccPos);
                    break;
                }
            }

        }else accManageBean = accManageBeans.get(selectAccPos);
        accountText.setText(accManageBean.getTypename());
        accountBean.setAccount(accManageBean.getTypename());
    }

    // 获取当前时间，显示在timeText中
    private void setInitTime() {
        if (type == 0){
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            String time = simpleDateFormat.format(date);
            timeText.setText(time);
            accountBean.setTime(time);

            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            accountBean.setYear(year);
            accountBean.setMonth(month);
            accountBean.setDay(day);
        }
        else{
            timeText.setText(accountBean.getTime());
        }
    }

    private void setGVListener() {
        typeGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.selectPos = position;
                adapter.notifyDataSetChanged(); //提示绘制发生变化
                TypeBean typeBean = typeList.get(position);

                typeText.setText(typeBean.getTypename());
                typeImage.setImageResource(typeBean.getsImageId());

                accountBean.setTypename(typeBean.getTypename());
                accountBean.setsImageId(typeBean.getsImageId());
            }
        });
    }

    public void loadDataGrid() {
        typeList = new ArrayList<>();
        adapter = new TypeBaseAdapter(getContext(), typeList);
        typeGrid.setAdapter(adapter);
    }

    private void initView(View view) {

        keyboardView = view.findViewById(R.id.frag_record_keyborad);
        moneyEdit = view.findViewById(R.id.frag_record_et_money);
        typeImage = view.findViewById(R.id.frag_record_iv);
        typeGrid = view.findViewById(R.id.frag_record_gv);
        typeText = view.findViewById(R.id.frag_record_tv_type);
        beizhuText = view.findViewById(R.id.frag_record_tv_beizhu);
        accountText = view.findViewById(R.id.frag_record_tv_account);
        timeText = view.findViewById(R.id.frag_record_tv_time);


        beizhuText.setOnClickListener(this);
        timeText.setOnClickListener(this);
        accountText.setOnCreateContextMenuListener(this);

        // 让自定义软键盘显示出来
        KeyBoardUtils boardUtils = new KeyBoardUtils(keyboardView, moneyEdit, type);
        boardUtils.showKeyboard();

        // 设置接口，监听确定按钮被点击了
        boardUtils.setOnEnsureListener(new KeyBoardUtils.OnEnsureListener() {
            @Override
            public void onEnsure(int type) {
                //点击了确定按钮
                // 获取输入钱数
                String moneyStr = moneyEdit.getText().toString();
                if (TextUtils.isEmpty(moneyStr) || moneyStr.equals("0")) {
                    getActivity().finish();
                    return;
                }
                float money = Float.parseFloat(moneyStr);
                accountBean.setMoney(money);

                if (type == 0){
                    //获取记录的信息，保存在数据库当中
                    saveAccountToDB();
                }else{
                    // 修改其中的内容
                    alterAccountToDB();
                }
                DBManager.alterItemFromAccmanagetbById(accManageBean.getId(),accManageBean);

                //返回上一级页面
                getActivity().finish();
            }
        });
    }

    // 抽象方法作用：让子类一定要重写这个方法
    public abstract void saveAccountToDB();

    public abstract void alterAccountToDB();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.frag_record_tv_time:
                showTimeDialog();
                break;
            case R.id.frag_record_tv_beizhu:
                showBZDialog();
                break;
        }
    }

    //弹出显示时间对话框
    private void showTimeDialog() {
        SelectTimeDialog dialog = new SelectTimeDialog(getContext());
        dialog.show();
        //设定确定按钮被点击了的监听器
        dialog.setOnEnsureListener(new SelectTimeDialog.OnEnsureListener() {
            @Override
            public void onEnsure(String time, int year, int month, int day) {
                timeText.setText(time);
                accountBean.setYear(year);
                accountBean.setMonth(month);
                accountBean.setDay(day);
            }
        });
    }

    // 弹出备注对话框
    public void showBZDialog() {
        final BeiZhuDialog dialog = new BeiZhuDialog(getContext());
        dialog.show();
        dialog.setDialogSize();
        dialog.setOnEnsureListener(new BeiZhuDialog.OnEnsureListener() {
            @Override
            public void onEnsure() {
                String msg = dialog.getEditText();
                if (!TextUtils.isEmpty(msg)) {
                    beizhuText.setText(msg);
                    accountBean.setBeizhu(msg);
                }
                dialog.cancel();
            }
        });
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        for (int i = 0; i < accManageBeans.size(); i++){
            if (item.getItemId() == menuId[i]){
                selectAccPos = i;
                accManageBean = accManageBeans.get(selectAccPos);
                accountText.setText(accManageBean.getTypename());
                accountBean.setAccount(accManageBean.getTypename());
            }
        }

        return false;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        MenuItem[] menuItems = new MenuItem[accManageBeans.size()];
        menuId = new int[accManageBeans.size()];

        for (int i = 0; i < accManageBeans.size(); i++){
            menuId[i] = accManageBeans.get(i).getId();
            String typename = accManageBeans.get(i).getTypename();
            menuItems[i] = menu.add(Menu.NONE,menuId[i],menuId[i],typename);
            menuItems[i].setOnMenuItemClickListener(this);
        }

    }
}